# Definition for a binary tree node.
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def goodNodes(self, root: Optional[TreeNode]) -> int:
        ans = 0

        def dfs(root: Optional[TreeNode], path):
            nonlocal ans
            if root.val >= path:
                ans += 1

            nxt = max(path, root.val)
            if root.left:
                dfs(root.left, nxt)
            if root.right:
                dfs(root.right, nxt)

        dfs(root, -1000000)
        return ans
